package org.yeruyi.common.activity;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;


import org.yeruyi.common.R;
import org.yeruyi.common.fragment.RoyBaseFragment;
import org.yeruyi.common.inter.IRoyBaseApplication;
import org.yeruyi.common.presenter.RoyBasePresenter;
import org.yeruyi.common.inter.RoyBaseView;
import org.yeruyi.common.ui.CustomMsgDialog;
import org.yeruyi.common.ui.CustomProcessDialog;
import org.yeruyi.common.util.ScreenUtil;

import java.util.List;

import butterknife.ButterKnife;


/**
 * Author：yeruyi
 * Date：2017/3/12
 * Version：v1.0
 * Note:
 * <p>
 * 2017年03月12日 新建封装项目
 * 2018年1月24日 对部分代码注释进行整理修改
 * 2018年03月18日 增加Application相关接口，并增加对应方法
 */

public abstract class RoyBaseActivity extends AppCompatActivity implements RoyBaseView {

    private static final String TAG = "[RoyBaseActivity]";

    // 状态栏默认颜色
    private static final int TOOLBAR_COLOR = R.color.default_toolbar_color;
    // P
    public RoyBasePresenter mPresenter;
    //进度窗
    private CustomProcessDialog mProcess;
    //信息窗
    private CustomMsgDialog mCustomMsgDialog;
    // 是否正在展示窗口标志位
    private boolean isDialogShowing = false;
    // 是否是dialog模式
    private boolean isAsDialogModel = false;
    // application
    private IRoyBaseApplication mApplication;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!initTitleStyle()) {
            initTitleDefault();
        }
        setContentView(initLayout());
        ButterKnife.bind(this);
        mPresenter = initPresenter();
        if (mPresenter != null)
            mPresenter.onViewInit();
        initBaseView();
        initActionBar();
        initViewEvent();
        if (mPresenter != null)
            mPresenter.onViewReady(getIntent());
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mPresenter != null)
            mPresenter.onViewStart();
    }

    @Override
    protected void onDestroy() {
        // 销毁自己的UI组件
        if (mProcess != null && mProcess.isShowing()) {
            dismissProcessDialog();
        }

        if (mPresenter != null) {
            mPresenter.destroy();
        }
        super.onDestroy();
    }

    /**
     * init this base view
     */
    private void initBaseView() {
        this.mProcess = new CustomProcessDialog.Builder(this).init();
        if (isAsDialogModel) {
            //定义弹出框，防止弹出框的高度和宽度变形
            WindowManager m = getWindowManager();
            Display d = m.getDefaultDisplay();//为获取屏幕宽、高
            WindowManager.LayoutParams p = getWindow().getAttributes();//获取对话框当前的参数值
            p.height = (int) (d.getHeight() * 1.0);//高度设置为屏幕的1.0
            p.width = (int) (d.getWidth() * 1.0); //宽度设置为屏幕的1.0
            //p.alpha = 1.0f;//设置本身透明度
            p.dimAmount = 0.8f; //设置黑暗度
            getWindow().setAttributes(p);//设置生效
        }
    }

    /**
     * 是否作为弹窗模式启动
     *
     * @param isAsDialogModel 弹窗模式
     */
    protected void isAsDialogModel(boolean isAsDialogModel) {
        this.isAsDialogModel = isAsDialogModel;
    }

    /**
     * initViewLayoutID
     */
    protected abstract int initLayout();

    /**
     * initPresenter
     *
     * @return 初始化Presenter
     */
    protected abstract RoyBasePresenter initPresenter();

    /**
     * 初始化actionBar，已有基本布局
     */
    protected abstract void initActionBar();


    /**
     * init view Event
     */
    protected abstract void initViewEvent();

    /**
     * init title Layout
     * if the callback is true the system will follow the other style
     * is false the system will follow the default style
     */
    protected abstract boolean initTitleStyle();

    /**
     * Push the fragment
     *
     * @param containerID replace fragment's layoutId
     * @param fragment    need to replace fragment.
     */
    public void pushFragment(int containerID, RoyBaseFragment fragment) {
        if (fragment != null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(containerID, fragment)
                    .addToBackStack(((Object) fragment).getClass().getSimpleName())
                    .commitAllowingStateLoss();
        }

    }

    public void popFragment() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            getSupportFragmentManager().popBackStack();
        } else {
            finish();
        }
    }

    @Override
    public void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(RoyBaseActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean showProcessDialog(String msg) {
        if (isDialogShowing) {
            return false;
        }
        mProcess = null;
        mProcess = new CustomProcessDialog.Builder(this).setMessage(msg).init();
        isDialogShowing = true;
        mProcess.show();
        return true;
    }

    @Override
    public boolean dismissProcessDialog() {
        if (mProcess != null && isDialogShowing) {
            mProcess.dismiss();
            isDialogShowing = false;
            mProcess = null;
            return true;
        } else {
            Log.e(TAG, "dismissProcessDialog: 结束进度窗，[mProcess is null?]" + (mProcess == null) + "[isDialogShowing]" + isDialogShowing);
            return false;
        }
    }

    @Override
    public Context getActivityContext() {
        return this;
    }

    @Override
    public void finishActivity() {
        this.finish();
    }


    protected void initTitleDefault() {
        ScreenUtil.setWindowStatusBarColor(this, R.color.default_toolbar_color);
    }

    @Override
    public void finishActivityWithResultIntent(int result, Intent intent) {
        setResult(result, intent);
        finishActivity();
    }

    @Override
    public void finishActivityWithResult(int result) {
        setResult(result);
        finishActivity();
    }


    @Override
    public void skipActivityForResult(Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void skipActivityWithIntent(Intent intent, boolean isFinished) {
        startActivity(intent);
        if (isFinished) {
            finish();
        }
    }

    @Override
    public void registerReceiverFromPresenter(BroadcastReceiver receiver, IntentFilter intentFilter) {
        registerReceiver(receiver, intentFilter);
    }

    @Override
    public void unregisterReceiverFromPresenter(BroadcastReceiver receiver) {
        unregisterReceiver(receiver);
    }

    @Override
    public void bindServiceFromPresenter(ServiceConnection serviceConnection, Intent intent) {
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void unbindServiceFromPrsenter(ServiceConnection serviceConnection) {
        unbindService(serviceConnection);
    }

    @Override
    public boolean showMsgDialog(String msg, String poText, String negaText, DialogInterface.OnClickListener positiveListener, DialogInterface.OnClickListener negativeListener) {
        if (positiveListener == null || negativeListener == null) {
            return false;
        }
        if (poText.equals("")) {
            poText = getResources().getString(R.string.custom_msg_dialog_confirm);
        }
        if (negaText.equals("")) {
            negaText = getResources().getString(R.string.custom_msg_dialog_cancel);
        }
        mCustomMsgDialog = new CustomMsgDialog.Builder(this)
                .setMessage(msg)
                .setPositiveButton(poText, positiveListener)
                .setNegativeButton(negaText, negativeListener)
                .create();
        mCustomMsgDialog.show();
        return true;
    }

    @Override
    public boolean dismissMsgDialog() {
        if (mCustomMsgDialog == null) {
            return false;
        }
        mCustomMsgDialog.dismiss();
        return true;
    }


    @Override
    public boolean showEditDialog(String title, String ediTextHint, DialogInterface.OnClickListener confirm, DialogInterface.OnClickListener cancel) {
        if (confirm == null || cancel == null) {
            return false;
        }
        if (isDialogShowing) {
            return false;
        }

        return true;
    }

    @Override
    public boolean dismissEditDialog() {

        return true;
    }

    @Override
    public void reqGrantedPermission(String[] permission) {
        RoyPermissionActivity.reqCheckPermissionWithRequest(this, permission);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RoyPermissionActivity.REQ_PERMISSION: {
                if (!(data == null || data.getExtras() == null || data.getExtras().getStringArrayList(RoyPermissionActivity.PERMISSION_DENIED_KEY) == null)) {
                    List<String> deniedPermissions = data.getExtras().getStringArrayList(RoyPermissionActivity.PERMISSION_DENIED_KEY);
                    if (deniedPermissions.size() != 0) {
                        permissionChecked(false, deniedPermissions);
                    }
                } else {
                    permissionChecked(true, null);
                }
                break;
            }
        }
    }

    /**
     * 处理授权情况
     *
     * @param deniedPermissions 未授权权限列表
     */
    protected void permissionChecked(boolean isAllAllowed, List<String> deniedPermissions) {

    }

    @Override
    public void sendMessage2Application(int what) {
        sendMessage2Application(what, 0, 0, null);
    }

    @Override
    public void sendMessage2Application(int what, Bundle extraData) {
        sendMessage2Application(what, 0, 0, extraData);
    }

    @Override
    public void sendMessage2Application(int what, int arg1, int arg2) {
        sendMessage2Application(what, arg1, arg2, null);
    }

    @Override
    public void sendMessage2Application(int what, int arg1, int arg2, Bundle extraData) {
        Message message = new Message();
        message.what = what;
        message.setData(extraData);
        if (getApplication() instanceof IRoyBaseApplication) {
            if (mApplication == null) {
                mApplication = (IRoyBaseApplication) getApplication();
            }
            mApplication.sendApplicationMsg(message);
        } else {
            Log.e(TAG, "sendMessage2Application: 发送数据失败，Application类未能引入接口IRoyApplication");
        }
    }

    @Override
    public Application doGetApplication() {
        return getApplication();
    }
}
